package com.fjnldx.mes.service.scheduling;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjnldx.mes.domain.domainReq.*;
import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.domainRes.Results;
import com.fjnldx.mes.domain.pojo.*;
import com.fjnldx.mes.mapper.common.MesContainerMapper;
import com.fjnldx.mes.mapper.scheduling.DevSnSelectedStatusMapper;
import com.fjnldx.mes.mapper.scheduling.SchedulingMapper;
import com.fjnldx.mes.mapper.scheduling.SchedulingPersonnelMapper;
import com.fjnldx.mes.service.scheduling.impl.DevIServiceImpl;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class SchedulingService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    SchedulingMapper schedulingMapper;

    @Resource
    SchedulingPersonnelMapper schedulingPersonnelMapper;

    @Resource
    DevSnSelectedStatusMapper devSnSelectedStatusMapper;
    @Resource
    DevIServiceImpl devIService;
    @Resource
    MesContainerMapper mesContainerMapper;

    /**
     * 设置机台选择状态
     */
    public Result setDevSnSelectedStatus(DevSnSelectedStatusPojo params, String[] devSnList) {
        if (params.getTime() == null) {
            return Result.error("时间不能为空");
        }
        QueryWrapper<DevSnSelectedStatusPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply(String.format("DATEDIFF(time,'%s')=0", params.getTime()));
        devSnSelectedStatusMapper.delete(queryWrapper);
        ArrayList<DevSnSelectedStatusPojo> devPojoList = new ArrayList<>();
        for (String s : devSnList) {
            DevSnSelectedStatusPojo pojo = new DevSnSelectedStatusPojo();
            pojo.setGongxu(params.getGongxu());
            pojo.setDevSn(s);
            pojo.setStatus("1");
            pojo.setTime(params.getTime());
            pojo.setBc(params.getBc());
            devPojoList.add(pojo);
        }
        boolean b = devIService.saveBatch(devPojoList);
        return b ? Result.success("设置成功") : Result.error("系统异常");
    }

    /**
     * 获取机台选择状态
     */
    public Result getDevSnSelectedStatus(DevSnSelectedStatusReq params) {
        List<Map> devSnSelectedStatus = schedulingMapper.getDevSnSelectedStatus(params);
        return Result.success(devSnSelectedStatus);
    }

    /**
     * 获取工序设备号
     */
    public Result getEquipmentByGx(GongXu params) {
        List<Map<String, Object>> equipmentList = schedulingMapper.getEquipmentByGx(params);
        return Result.success(equipmentList);
    }

    /**
     * 人员管理-集团-级联
     */
    public Result queryPersonnelGroup() throws Exception {
        try {
            List<Group> list = schedulingMapper.queryPersonnelGroup();
            return Result.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 人员管理-集团-组织-级联
     */
    public Result queryPersonnelGroupAndOrg(Group data) throws Exception {
        try {
            List<GroupAndOrg> list = schedulingMapper.queryPersonnelGroupAndOrg(data);
            return Result.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 查询人员排班记录
     */
    public Results queryPersonnelClasses(SchedulingReq data, Page page) {
        if (data.getTime() == null || data.getBc() == null || data.getCurrent_gongxu() == null || data.getCurrent_work_type() == null) {
            return Results.error("请输入对应工序、工种、日期、班次");
        }
        IPage<Map<String, Object>> list = mesContainerMapper.queryScheduling(data, page);
        List<Object> objects = new ArrayList<>();
        // pz总类
        List<Map<String, Object>> pzs = mesContainerMapper.queryPzByGxAndNow(data);
        for (Map<String, Object> item : pzs) {
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("pz" + item.get("id"), item.get("pz"));
            objects.add(obj);
        }
        List<Map<String, Object>> records = list.getRecords();
        // 设置品种
        for (Map<String, Object> record : records) {
            // 工人对应pz
            HashMap<Object, Object> pzOfUserParams = new HashMap<>();
            pzOfUserParams.put("time", data.getTime());
            pzOfUserParams.put("bc", data.getBc());
            pzOfUserParams.put("current_gongxu", record.get("current_gongxu"));
            pzOfUserParams.put("name", record.get("name"));
            List<Map<String, Object>> maps = mesContainerMapper.queryPzByUserNameAndGx(pzOfUserParams);
            for (Map<String, Object> map : maps) {
                String pz = map.get("pz").toString();
                // 比对总类获取品种id
                for (Map<String, Object> item : pzs) {
                    if (item.get("pz").equals(pz)) {
                        // 获取设备范围
                        Map<String, Object> devMap = mesContainerMapper.queryDevSnAreaByUser(map);
                        String[] arr = devMap.get("devSnArea").toString().split(",");
                        record.put("pz" + item.get("id"), Arrays.asList(arr));
                    }
                }
            }
        }
        return Results.success(list, objects);
        //QueryWrapper<Scheduling> queryWrapper = new QueryWrapper<>();
        //if (!StringUtils.isEmpty(data.getBc()) && data.getBc() != null) {
        //    queryWrapper.eq("bc", data.getBc());
        //}
        //if (!StringUtils.isEmpty(data.getGh()) && data.getGh() != null) {
        //    queryWrapper.eq("gh", data.getGh());
        //}
        //if (!StringUtils.isEmpty(data.getCurrent_gongxu()) && data.getCurrent_gongxu() != null) {
        //    queryWrapper.eq("current_gongxu", data.getCurrent_gongxu());
        //}
        //if (!StringUtils.isEmpty(data.getCurrent_work_type()) && data.getCurrent_work_type() != null) {
        //    queryWrapper.eq("current_work_type", data.getCurrent_work_type());
        //}
        //if (!StringUtils.isEmpty(data.getDevSn()) && data.getDevSn() != null) {
        //    queryWrapper.eq("devSn", data.getDevSn());
        //}
        //if (data.getShare() != null) {
        //    queryWrapper.eq("share", data.getShare());
        //}
        //if (!StringUtils.isEmpty(data.getBc()) && data.getBc() != null) {
        //    queryWrapper.eq("bc", data.getBc());
        //}
        //if (data.getStart_time() != null) {
        //    queryWrapper.eq("start_time", data.getStart_time());
        //}
        //if (data.getEnd_time() != null) {
        //    queryWrapper.eq("end_time", data.getEnd_time());
        //}
        //if (!StringUtils.isEmpty(data.getCurrent_dh()) && data.getCurrent_dh() != null) {
        //    queryWrapper.eq("current_dh", data.getCurrent_dh());
        //}
        //Page list = schedulingMapper.selectPage(page, queryWrapper);
        //return Result.success(list);
    }

    /**
     * 移除该人员排班
     */
    public Result deletePersonnelClasses(SchedulingReqOfName data) {
        int i = mesContainerMapper.deletePersonnelClasses(data);
        return i > 0 ? Result.success("删除成功") : Result.success("系统异常");
    }


    /**
     * 新增人员排班
     */
    public Result addPersonnelClasses(Scheduling data) throws Exception {
        try {
            schedulingMapper.addPersonnelClasses(data);
            return Result.success("新增成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 修改人员排班
     */
    public Result modifyPersonnelClasses(SchedulingShow data) {
        List<PzPojo> pzPojoList = data.getPzPojoList();
        // 存放该名员工全部机台号
        ArrayList<String> delArr = new ArrayList<>();
        for (PzPojo pzPojo : pzPojoList) {
            delArr.addAll(pzPojo.getDevSnArea());
        }
        QueryWrapper<Scheduling> queryWrapper = new QueryWrapper<>();
        queryWrapper.notIn("devSn", delArr);
        //schedulingMapper.delete(queryWrapper);


        //int i = schedulingMapper.updateById(data);
        //return i > 0 ? Result.success("更新成功") : Result.success("系统错误");
        return Result.success(delArr);
    }

    /**
     * 新增人员信息（单个）
     *
     * @param data
     * @return
     */
    public Result addPersonnel(SchedulingPersonnel data) {
        String msg = data.saveCheck();
        if (!StringUtils.isEmpty(msg)) {
            return Result.error(msg);
        }
        //工号唯一，不能出现重复记录
        QueryWrapper<SchedulingPersonnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gh", data.getGh());
        Integer i = schedulingPersonnelMapper.selectCount(queryWrapper);
        if (i > 0) {
            return Result.error("工号重复");
        }
        int insert = schedulingPersonnelMapper.insert(data);
        return insert > 0 ? Result.success("新增成功") : Result.error("系统异常");
    }

    /**
     * 修改人员信息
     *
     * @param data
     * @return
     */
    public Result modifyPersonnel(SchedulingPersonnel data) {
        String msg = data.updateCheck();
        if (!StringUtils.isEmpty(msg)) {
            return Result.error(msg);
        }
        //工号唯一，不能出现重复记录
        QueryWrapper<SchedulingPersonnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gh", data.getGh());
        SchedulingPersonnel recode = schedulingPersonnelMapper.selectOne(queryWrapper);
        if (null == recode) {
            return Result.error("记录不存在");
        }
        data.setId(recode.getId());
        int insert = schedulingPersonnelMapper.updateById(data);
        return insert > 0 ? Result.success("更新成功") : Result.error("系统异常");
    }

    /**
     * 删除人员信息
     *
     * @param array
     * @return
     */
    public Result deletePersonnel(String[] array) {
        if (null == array || array.length <= 0) {
            return Result.error("参数错误");
        }
        QueryWrapper<SchedulingPersonnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("gh", array);
        int i = schedulingPersonnelMapper.delete(queryWrapper);
        return i > 0 ? Result.success("删除成功") : Result.error("系统异常");
    }

    /**
     * 多条件查询人员信息
     *
     * @param data
     * @return
     */
    public Result queryPersonnel(SchedulingPersonnelReq data) {
        QueryWrapper<SchedulingPersonnel> queryWrapper = new QueryWrapper<>();
        IPage<SchedulingPersonnel> page = new Page<>();
        if (-1 == data.getSize()) {
            page.setSize(9999999);
            page.setPages(1);
        } else {
            page.setSize(data.getSize());
            page.setPages(data.getPage());
        }
        if (!StringUtils.isEmpty(data.getGh()) && !"null".equals(data.getGh())) {
            queryWrapper.eq("gh", data.getGh());
        }
        if (!StringUtils.isEmpty(data.getBc()) && !"null".equals(data.getBc())) {
            queryWrapper.eq("bc", data.getBc());
        }
        if (!StringUtils.isEmpty(data.getCj()) && !"null".equals(data.getCj())) {
            queryWrapper.eq("cj", data.getCj());
        }
        if (!StringUtils.isEmpty(data.getWorkType()) && !"null".equals(data.getWorkType())) {
            queryWrapper.eq("work_type", data.getWorkType());
        }
        if (!StringUtils.isEmpty(data.getGongxu()) && !"null".equals(data.getGongxu())) {
            queryWrapper.eq("gongxu", data.getGongxu());
        }
        if (!StringUtils.isEmpty(data.getName()) && !"null".equals(data.getName())) {
            queryWrapper.like("name", data.getName());
        }
        if (!StringUtils.isEmpty(data.getOrg()) && !"null".equals(data.getOrg())) {
            queryWrapper.eq("org", data.getOrg());
        }
        if (!StringUtils.isEmpty(data.getGroup()) && !"null".equals(data.getGroup())) {
            queryWrapper.eq("`group`", data.getGroup());
        }
        IPage<SchedulingPersonnel> result = schedulingPersonnelMapper.selectPage(page, queryWrapper);
        Map<String, Object> res = new HashMap<>();
        res.put("dataList", result.getRecords());
        res.put("total", result.getTotal());
        return Result.success(res);
    }

    public String getChineseToPinyin(String str) {
        // 中文字符串转换为字符数组
        char[] chars = str.toCharArray();
        // 设置转换格式
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        // 小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 无声调，WITH_TONE_NUMBER表示用数字表示声调, WITH_TONE_MARK表示用声调符号表示
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // 特殊拼音ü的的显示格式
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder result = new StringBuilder();
        try {
            for (char c : chars) {
                // 通过正则判断是否为汉字字符
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] s = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    result.append(s[0]);
                } else {
                    result.append(c);
                }
            }
            return result.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return result.toString();
    }
}
